<template>
<div class="contest-detail">
    <div class="contest-header">
        <div style="padding-left: 30%;">

        <h1>
          {{ item.title }}
            <el-tag class="status" v-if="item.status==0"  size="mini" type="success" effect="dark">未开始</el-tag>
        <el-tag class="status" v-if="item.status==1"  size="mini" type="danger" effect="dark">进行中</el-tag>
        <el-tag class="status" v-if="item.status==2"  size="mini" type="info" effect="dark">已结束</el-tag>
        </h1>

        <div>
            {{item.startTime}} 至 {{ item.endTime }}

            <br/><span>时长: {{getTimeDuration(item.startTime,item.endTime)}} </span>

        </div>
        <div >
            已有{{ item.registerPerson }}人报名
          <a href="javascript:void(0)"
             style="color: white;margin-left: 200px;"
             @click="copyContent('/#/main/contest/detail/'+$route.params.id)">
          <i class="fa fa-share-square-o"></i>  分享比赛
        </a>
        </div>

        <div>
            <!-- 倒计时 -->
            <el-statistic v-if="item.status==0" @finish="setStatus(1)" :value="new Date(item.startTime).getTime()" time-indices title="" format="HH:mm:ss"  class="count-down">
                <template slot="prefix"> 距比赛 </template>
            </el-statistic>
            <el-statistic v-if="item.status==1" @finish="setStatus(2)" :value="(new Date(item.endTime)).getTime()" time-indices title="" format="HH:mm:ss" class="count-down">
                <template slot="prefix"> 距结束 </template>
            </el-statistic>
        </div>


        <div style="height:10px"></div>
        </div>

        <el-progress v-if="false" style="margin-bottom: 10px;margin-top: 35px;margin-left: 10px;margin-right: 10px;"
        :percentage="percentages" :format="format" define-back-color="gray" ></el-progress>
    </div>
    <div class="contest-body">
        <!-- 比赛已结束或（比赛进行中已报名） -->
        <el-tabs v-model="activeName" :before-leave="handleClick" v-if="item.status==2||(item.status==1&&registered)">
            <el-tab-pane label="比赛说明" name="description">
                <mavonEditor :ishljs = "true" previewBackground="#eeeeee" :editable="false" :toolbarsFlag = "false" :defaultOpen="'preview'" :subfield="false" v-model="item.description" style="min-height: 20px"/>

            </el-tab-pane>

            <el-tab-pane label="题目" name="question" >
                <!-- 题目列表 -->
                <el-table :data="item.problems" style="width:860px;">
                    <el-table-column
                        label="题号"
                        width="80">
                        <template slot-scope="scope">
                            <router-link :to="'/main/contest/problem/'+scope.row.id+'/'+scope.row.contestId">
                                {{ $MyUtils.numToString(scope.row.sequence-1) }}
                            </router-link>

                        </template>
                    </el-table-column>
                    <el-table-column
                        label="标题"
                        width="400">
                        <template slot-scope="scope">
                            <router-link  target="_blank" :to="'/main/contest/problem/'+scope.row.id+'/'+scope.row.contestId">{{ scope.row.contestTitle }}</router-link>
                        </template>
                    </el-table-column>
                    <el-table-column label="通过率" width="120">
                        <template slot-scope="scope">
                            {{ scope.row.acceptSum }} / {{ scope.row.submitSum }}
                        </template>
                    </el-table-column>
                    <el-table-column label="已通过的代码" width="130" v-if="item.status==2">
                        <template slot-scope="scope">
                            <router-link target="_blank" :to="'/main/status?errorStatus=0&problemId='+scope.row.problemId" style="color:#25bb9b">点击查看</router-link>
                        </template>
                    </el-table-column>
                    <el-table-column label="我的提交" width="120">
                        <template slot-scope="scope">
                            <div v-html="formatterStatus(scope.row)"></div>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane  label="提交" name="submit">
                <submitList :contestProblemList="item.problems" :showDetail="item.status==2"></submitList>
                <footer style="height: 200px;"></footer>
            </el-tab-pane>
            <!-- 排名，榜单 -->
            <el-tab-pane label="排名" name="rank">
                <a href="javascript:void(0)" style="float: right;text-align: center;color: gray;" @click="copyContent()">
                    <i class="fa fa-share-square-o"></i>  分享榜单
                </a>

              <a v-if="isAdmin()"  href="javascript:void(0)" @click="downRank($route.params.id)" style="float: right;text-align: center;color: gray;margin-right: 10px;">
                 导出榜单
              </a>
                <Rank :contestId="$route.params.id" :loginUser="loginUser()" style="overflow-x: auto;width: 800"></Rank>

            </el-tab-pane>
            <el-tab-pane label="公告" name="announcement">
              <ContestAnnounce :contest="item"></ContestAnnounce>
            </el-tab-pane>
            <el-tab-pane label="讨论" name="comment" ></el-tab-pane>
        </el-tabs>
        <!-- 未报名或比赛未开始 -->
        <div v-if="item.status==0||(item.status==1&&!registered)" style="text-align: left;">
                <!-- 报名 -->
                <el-button style="margin: 30px;width: 90%;" type="success" v-if="!registered" round @click="saveRegister(item)">报名</el-button>
                <el-button style="margin: 30px;width: 90%;" type="info" round v-if="registered&&item.status==0" @click="cancelRegister(item)">已报名</el-button>

            <h3 >比赛说明</h3>
            <mavonEditor :ishljs = "true" previewBackground="#eeeeee" :editable="false" :toolbarsFlag = "false" :defaultOpen="'preview'" :subfield="false" v-model="item.description" style="min-height: 20px"/>
        </div>
    </div>
    <!-- <footer style="height: 200px;">111111111111</footer> -->
</div>
</template>

<script  lang="ts">
import * as contestApi from '@/api/contest'
import {isAdmin} from '@/utils/auth';
import { mavonEditor } from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';
import {loginUser} from '@/utils/auth.js'
export default {
    name: 'contestDetail',
    data() {
        return {
            item:{},
            percentages:100,
            activeName:"question",
            registered:false,
        };
    },
    components:{
        mavonEditor,
        Rank: () => import('@/components/contest/rank.vue'),
        ContestAnnounce: () => import('@/components/contest/contestAnnouncement.vue'),
        submitList: () => import('@/components/contest/submitList.vue'),
    },
    methods: {

      //下载榜单
      downRank(id){
        contestApi.downRank({"id":id}).then(res=>{
          console.info(res)
          // console.info(res.headers.toJSON())
          // console.info(res.getHeader("Content-Disposition"))
          var fileName = null;
          if(res.headers['content-disposition'])fileName = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1])
          else fileName = "榜单"
          //下载文件
          var content = res.headers['content-type'];
          // console.info(content);
          let blob = new Blob([res.data], {type: content})
          let objectUrl = URL.createObjectURL(blob) // 创建URL
          const link = document.createElement('a')
          link.href = objectUrl
          // link.download = '.xlsx'// 自定义文件名
          //这里是获取后台传过来的文件名
          link.setAttribute("download",fileName)
          link.click() // 下载文件
          URL.revokeObjectURL(objectUrl) // 释放内存
        })
      },
      loginUser(){
        return loginUser();
      },
      isAdmin(){
        return isAdmin();
      },
      // 获取时间差
      getTimeDuration(time1,time2){
        var x = new Date(time2).getTime()-new Date(time1).getTime(); //毫秒
        var min = Math.floor(x/1000/60);  //分钟
        var hour = Math.floor(min/60);
        var res = "";
        if(hour!=0)res+=hour + '小时';
        if(min%60!=0)res += (min%60)+"分钟";
        return res;
      },
      //设置比赛的状态值
      setStatus(status){
        this.item.status = status;
        // this.$set(this.listData,index,this.listData[index])
      },
      getItemById(){
        contestApi.getDetail({"id":this.$route.params.id}).then(async res=>{
            if(res.data.success){
                this.item = res.data.data;
                await contestApi.contesResgister({"id":this.$route.params.id}).then(res3=>{
                    if(res3.data.data){
                        this.registered = true;
                        // console.info(this.item)
                    }else{
                        this.registered = false;
                    }
                })
            }
        })
      },
      format(){
        var x = new Date(this.item.endTime).getTime()-new Date(this.item.startTime).getTime(); //毫秒,总时长
        var y = new Date(this.item.endTime).getTime() - new Date().getTime();  //距离结束时间
        if(y>x){
            this.percentages = 100;
            return "未开始";

        }else if(y<0){
            this.percentages = 0;
            return "已结束";
        }else{
            this.percentages = y/x;
            var min = Math.floor(y/1000/60);  //分钟
            var hour = Math.floor(min/60);
            var res = "";
            if(hour!=0)res+=hour + '小时';
            if(min%60!=0)res += (min%60)+"分钟";
            return res;
        }
      },
      //选择
      handleClick(tab, event) {
      console.log(tab, event);

      if(tab=='comment') {

        // this.$router.push({path: , target: "_blank"});
        let routeData = this.$router.resolve({ path: '/main/comment?fatherId=' + this.item.id });
        window.open(routeData.href, '_blank');
        return false;
      }
      },

      //报名
      saveRegister(data){
        // var password = "";
        if(data.auth==1){  //需要密码
          this.$prompt('需要比赛邀请码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {  //需要邀请码
          contestApi.saveRegister({"contestId":data.id,"password":value}).then(res=>{
            if(res.data.success){
              this.$message({"type":"success",message:"报名成功"});
              this.registered = true;
              this.item.registerPerson++;
            //   this.$set(this.listData,index,this.listData[index])
              // data.registered = true;
            }
          })
        });

        }else{ //不需要邀请码
          contestApi.saveRegister({"contestId":data.id}).then(res=>{
            if(res.data.success){
              this.$message({"type":"success",message:"报名成功"});
              this.registered = true;
              this.item.registerPerson++;
            //   this.$set(this.listData,index,this.listData[index])
              // data.registered = true;
            }
          })
        }

      },
      //取消报名
      cancelRegister(data){
        contestApi.cancelRegister({"id":data.id}).then(res=>{
          if(res.data.success){
            this.$message({type:"info",message:"取消报名成功"});
            this.registered = false;
            this.item.registerPerson--;
            // this.$set(this.listData,index,this.listData[index])
          }
        });
      },
      /**
       * 题目提交状态重定义输出显示
       * @param row
       */
       formatterStatus(row) {
        // console.info(row.status)
          if (row.status == -1) {return this.$t("problemMode.status.fir");}
          else if (row.status == 0) {return '<span style="color:#25bb9b;">'+this.$t("problemMode.status.sec")+'</span>';}
          else if (row.status == 1) {return '<span style="color:#ff7a38;">'+this.$t("problemMode.status.thi")+"</span>";}
      },
      /**
         * 复制内容
         * @param {String} value 需要复制的内容
         * @param {String} type 元素类型 input, textarea
         */
        copyContent(value, type = 'input') {
            if(!value)value = location.host+'/#/contest/rank/'+this.$route.params.id
            else value = location.host+value;
            const input = document.createElement(type);
            input.setAttribute('readonly', 'readonly'); // 设置为只读, 防止在 ios 下拉起键盘
            // input.setAttribute('value', value); // textarea 不能用此方式赋值, 否则无法复制内容
            input.value = value;
            document.body.appendChild(input);
            input.setSelectionRange(0, 9999); // 防止 ios 下没有全选内容而无法复制
            input.select();
            document.execCommand('copy');
            document.body.removeChild(input);
            this.$message("复制成功!");
        }

    },
    created(){
        // this.$route.hash = "1234"
        if(this.$route.params.activeName){
            this.activeName = this.$route.params.activeName;
        }
        this.getItemById();
    },


}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.contest-detail .contest-header{

    background-image: url(../../assets/contest-background.jpg);
    background-color: #031022;
    margin-left: -2%;
    /* margin-top: -1rem; */
    /* width:100%; */
    /* height: 100vh; */

    color: #ffffff;
    background-size: 100% auto;
    /* background-repeat:no-repeat; */
    background-repeat:repeat-y;
    text-align: left;
}
.contest-detail .contest-header > div > div{

    margin-top: 15px;
}
.contest-detail .contest-header h1{
    font-size: 32px;
    font-weight: 400;
    padding-top: 2%;
    position: relative;
}
.contest-detail .contest-header h1 > span{
    position: absolute;
    margin-left: 10px;
    margin-top: 10px;
}
.contest-detail{
    margin-top: -2rem;
    width:100%;
}
.contest-detail .contest-body{
    font-size: 16px;
    margin-left: 15%;
    width: auto;
    max-width: 70%;

}
</style>
<style>
.contest-detail .contest-header > div .con{

    /* margin-top: -1rem; */
    /* width:100%; */
    /* height: 100vh; */
    color: #ffffff;
    text-align: left;
    width: auto;
    display: block;
}
</style>
